//
//  FileWindowController.m
//  TcpTest_Client
//
//  Created by SCARLETTSUN on 12-8-1.
//  Copyright (c) 2012年 tencent. All rights reserved.
//

#import "FileWindowController.h"
#import "HiQProgressCellView.h"
#import "FileListenSocket.h"
#import "FileSocket.h"
#import "MainWindowController.h"



@implementation FileWindowController
@synthesize fileListArray;
@synthesize fileWindow;

static NSInteger ifShow = UnOpen;
static FileWindowController *fileWindowController;

+ (BOOL)FileIfShow
{
    return ifShow;
}

+ (FileWindowController *)fileWindowController
{
    if (fileWindowController == Nil)
    {
       fileWindowController = [[FileWindowController alloc] init];
        ifShow = UnOpen;
    }
    return fileWindowController;
}

- (id)init
{
    self = [super init];
    if (self) {
        fileListArray = [[NSMutableArray alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:) name:NSWindowWillCloseNotification object:self.fileWindow];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(NSString *)windowNibName 
{
    return @"FileTableView";
}

- (void)windowDidLoad
{
    [super windowDidLoad]; 
    [fileTableView reloadData]; 
    ifShow = Open; 
}

- (void)windowWillClose:(NSNotification *)notification 
{
  if ([notification object] == self.fileWindow) /*停止传输文件，close socket*/
  {
     @synchronized([FileListenSocket fileSocketsQueue])
      {
          for (FileSocket *sock in [FileListenSocket fileSocketsQueue]) 
          {
              //sock.ifInitiativeStop = YES; //主动关闭面板
              [sock.fileAsynSocket disconnect];
          }
      }
    ifShow = Close;
    fileWindowController = nil; 
   }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
	NSLog(@"Table section changed: keyPath = %@, %@", keyPath, [object selectionIndexes]);
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return fileListArray.count;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row 
{
    HiQProgressCellView  *cellView = [tableView makeViewWithIdentifier:@"MainCell" owner:self];
    FileEntity * file = [fileListArray objectAtIndex:row];
    cellView = [cellView initWithFileEntity:file];
    return cellView;
}    

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row 
{
    return FILEPANELHEIGHT;
}

- (IBAction)btnRemoveRowClick:(id)sender 
{
    NSInteger row = [fileTableView rowForView:sender];
    if (row != -1) 
    {
        FileEntity *_entity = [fileListArray objectAtIndex:row];
        if(_entity.delegate != nil)
        {
            if (_entity.fileState == EntityWaiting) {
                [_entity.delegate doRejectFile];
            }
            else {
                [_entity.delegate doTerminateFile];
            }
        }
    }                                                                                                                  
}

- (void)_selectRowStartingAtRow:(NSInteger)row 
{
    if ([fileTableView selectedRow] == -1) 
    {
        if (row == -1)
            row = 0;
        row++;
        [fileTableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
    }
}

- (IBAction)btnRevealInFinderSelected:(id)sender 
{
    NSInteger row = [fileTableView rowForView:sender]; 
    if(row < 0 || row >= [fileListArray count] )
        return;
    FileEntity *entity = [fileListArray objectAtIndex:row];
    if (entity != nil) 
    {
        if (entity.fileState == EntityWaiting) 
        {
            if (entity.delegate != nil) 
            {
                [entity.delegate doAcceptFile];
            }
        }
        else 
        {
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if (![fileManager fileExistsAtPath:[entity.fileUrl path]]) 
            {
                [self showError:[NSString stringWithFormat:@"%@ doesnt exist",[entity.fileUrl path]]];
                return;
            }
            [[NSWorkspace sharedWorkspace] selectFile:[entity.fileUrl path] inFileViewerRootedAtPath:nil];
        }
    }

}

- (void) updateFileProgress
{
    [fileTableView reloadData];
}

-(void)showError:(NSString *)infoText
{
    NSAlert *alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:NSLocalizedString(@"确定", nil)];
    [alert setMessageText:NSLocalizedString(@"浏览文件失败",nil)];
    [alert setInformativeText:NSLocalizedString(infoText, nil)];
    [alert setAlertStyle:NSWarningAlertStyle];
    [alert beginSheetModalForWindow:[NSApp mainWindow] modalDelegate:self didEndSelector:@selector(sheetClosed:returnCode:contextInfo:) contextInfo:nil];
}

-(void)sheetClosed:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
    if (returnCode == NSAlertDefaultReturn) {
        [(__bridge_transfer NSWindow *)contextInfo close];
    }
}

@end
